package main.chapter4

val add5 = { i: Int -> i + 5 }
val multiply2 = { i: Int -> i * 2 }
fun main(args: Array<String>) {
    println(multiply2(add5(5))) //20

    val add5AndMultiply2 = add5 andThen multiply2
    println(add5AndMultiply2(5)) //m(x)=f(g(x)) (5+5)*2=20

    val add5ComposeMultiply2 = add5 compose multiply2
    println(add5ComposeMultiply2(5)) //m(x)=g(f(x)) 5*2+5=15
}

//infix中缀表达式，扩展方法扩展Function1,Function1代表参数一个的函数两个泛型分别代表参数类型和返回值类型
infix fun <P1, P2, R> Function1<P1, P2>.andThen(function: Function1<P2, R>): Function1<P1, R> {
    return fun(p1: P1): R {
        return function.invoke(this.invoke(p1))
    }
}

infix fun <P1, P2, R> Function1<P2, R>.compose(function: Function1<P1, P2>): Function1<P1, R> {
    return fun(p1: P1): R {
        return this.invoke(function.invoke(p1))
    }
}